<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
error_reporting(1);
defined ('IN_AGORA') or die;

define('_DEF_PARAMS',
'notifyEmailSystem=1
privacyProfileView=0
privacyPhotoView=0
privacyFriendsView=0
privacyVideoView=1
notifyEmailMessage=1
notifyEmailApps=1'
);

define('QUERY_LIMIT', 100);

class ConvertersModel extends Model {
	var $kunena_version;
	var $kunena_prefix;
	var $config_model;
	var $agora_config;
	var $group_model;
	var $upload_model;
	
	function __construct() {
		parent::__construct('bans');
		$this->config_model = & Model::getInstance('ConfigModel');
        $this->agora_config = $this->config_model->load();
		$this->group_model = & Model::getInstance('GroupModel');
		$this->upload_model = & Model::getInstance('UploadModel');
	}
	
	function start($forum='') {
		$this->_truncate_tables($forum);
		$this->_remove_indexes($forum); 
	}
	
	function end() {
		$this->_add_indexes();
		$this->_recount();
	}	
	
	function detect_kunena() {
		$this->kunena_version = '1.5';
		$this->kunena_prefix = 'fb';
		$this->db->setQuery('SELECT board_title FROM #__kunena_config LIMIT 1');
		$result = @$this->db->loadResult();
		if ($result) {
			$this->kunena_version = '1.6';
			$this->kunena_prefix = 'kunena';
		}
	}
	
	function export_users_kunena() {
		$offset = 0;
		$pref = $this->kunena_prefix;
		
		do {
			$have_data = false;		    
			$this->db->setQuery('SELECT * FROM #__' . $pref . '_users LEFT JOIN #__users ON userid=id ORDER BY userid LIMIT ' . $offset . ',' . QUERY_LIMIT);
			$ob_list = $this->db->loadAssocList();
			
			if (count($ob_list) > 0) {
				$have_data = true;
			}
			
			foreach ($ob_list as $ob) {
				//echo '<br>'.$ob['name'].' ('.$ob['userid'].")\n"; flush();
				
				$this->db->setQuery('SELECT time FROM #__' . $pref . '_messages WHERE userid ='.$ob['userid'].' ORDER BY time DESC LIMIT 1');
				$last_post = $this->db->loadResult();
				$this->db->setQuery('SELECT count(*) AS count FROM #__' . $pref . '_messages WHERE userid ='.$ob['userid']);
				list($post_count) = $this->db->loadResult();
				$this->db->setQuery('SELECT time FROM #__' . $pref . '_messages WHERE userid ='.$ob['userid'].' ORDER BY time ASC LIMIT 1');
				$registered = $this->db->loadResult();

				// Dataarray
				$todb = array(
					'id' => $ob['userid'],
					'jos_id' => $ob['userid'],
					'username' => $ob['username'],
					'email' => $ob['email'],
					'use_avatar ' => ($ob['avatar'] ? '1' : '0'),
					'num_posts' => $post_count,
					'last_post' => $last_post,
					'registered' => $registered,
					'signature'	=> $ob['signature'] ,
					'birthday' => $ob['birthdate'] ,
					'gender' => $ob['gender'],
					'location' => $ob['location'],
					'icq' => $ob['ICQ'], 
					'aim' => $ob['AIM'], 
					'msn' => $ob['MSN'], 
					'skype' => $ob['SKYPE'],
					'url' => $ob['websiteurl']
				);
				//echo '<pre>'; print_r($todb); echo '</pre>';		        
				$this->_insertdata('users', $todb);
				
				$this->group_model->addUser(1, $ob['userid'], 2);
				
				$agora_avatar_dir = JPATH_ROOT . DS . $this->agora_config['o_avatars_dir'];
				$kunena_avatar_dir = JPATH_ROOT . DS . 'media' . DS . 'kunena' . DS . 'avatars' . DS . 'resized' . DS . 'size72';
				
 				if (!is_dir($agora_avatar_dir)) mkdir($agora_avatar_dir);
				
				if ($ob['avatar'] && is_file($kunena_avatar_dir . DS .$ob['avatar']) && is_dir($agora_avatar_dir)) {
					copy($kunena_avatar_dir . DS .$ob['avatar'], $agora_avatar_dir . DS . $ob['userid'] . '.png');
				}
			}
			
			$offset += QUERY_LIMIT;
			
		} while ($have_data);		    		    
	}
	
	function export_users_ccboard() {
		$offset = 0;
		
		do {
			$have_data = false;		    
			$this->db->setQuery('SELECT * FROM #__ccb_users as cu LEFT JOIN #__users as u ON cu.user_id=u.id ORDER BY user_id LIMIT ' . $offset . ',' . QUERY_LIMIT);
			$ob_list = $this->db->loadAssocList();
			
			if (count($ob_list) > 0) {
				$have_data = true;
			}
						
			foreach ($ob_list as $ob) {
				$last_id = $ob['user_id'];
				//echo '<br>'.$ob['name'].' ('.$ob['userid'].")\n"; flush();
				
				$this->db->setQuery('SELECT post_time FROM #__ccb_posts WHERE post_user ='.$ob['user_id'].' ORDER BY post_time DESC LIMIT 1');
				$last_post = $this->db->loadResult();
				$this->db->setQuery('SELECT count(*) AS count FROM #__ccb_posts WHERE post_user ='.$ob['user_id']);
				list($post_count) = $this->db->loadResult();
				$this->db->setQuery('SELECT post_time FROM #__ccb_posts WHERE post_user ='.$ob['user_id'].' ORDER BY post_time ASC LIMIT 1');
				$registered = $this->db->loadResult();

				// Dataarray
				$todb = array(
					'id' => $ob['user_id'],
					'jos_id' => $ob['user_id'],
					'username' => $ob['username'],
					'email' => $ob['email'],
					'use_avatar ' => ($ob['avatar'] ? '1' : '0'),
					'num_posts' => $ob['post_count'],
					'last_post' => $last_post,
					'registered' => $registered,
					'signature' => $ob['signature'] ,
					'birthday' => $ob['dob'] ,
					'gender' => $ob['gender'],
					'location' => $ob['location'],
					'icq' => $ob['icq'],  
					'msn' => $ob['msn'], 
					'skype' => $ob['skype'],
					'yahoo' => $ob['yahoo'],
					'jabber' => $ob['jabber'],
					'url' => $ob['www']	 
				);
				//echo '<pre>'; print_r($todb); echo '</pre>';		        
				$this->_insertdata('users', $todb);
				
				$this->group_model->addUser(1, $ob['userid'], 2);
				
				if ($ob['avatar']) {
				
					$agora_avatar_dir = JPATH_ROOT . DS . $this->agora_config['o_avatars_dir'];
					$ccboard_avatar_dir = JPATH_ROOT . DS . 'components' . DS . 'com_ccboard' . DS . 'assets' . DS . 'avatar';
					if (!is_dir($agora_avatar_dir)) mkdir($agora_avatar_dir);
					
					// this block of code will be reworked in the future, there will be method to resize avatars...
					// but for now we use the resize method for attachments
					$agora_att_dir = JPATH_ROOT . DS . 'components' . DS . 'com_agora' . DS . 'img' . DS . 'members';
					if (!is_dir($agora_att_dir)) mkdir($agora_att_dir);
					$agora_att_dir = JPATH_ROOT . DS . 'components' . DS . 'com_agora' . DS . 'img' . DS . 'members' . DS . $ob['user_id'];
					if (!is_dir($agora_att_dir)) mkdir($agora_att_dir);
					if (is_dir($agora_att_dir) && is_dir($ccboard_avatar_dir) && is_file($ccboard_avatar_dir . DS .$ob['avatar'])) {
						copy($ccboard_avatar_dir . DS .$ob['avatar'], $agora_att_dir . DS . $ob['user_id'] . '.png');
					}
					if (is_file($agora_att_dir . DS . $ob['user_id'] . '.png')) {
						$this->upload_model->makeThumb($ob['user_id'], $ob['user_id'] . '.png', $this->agora_config['o_avatars_width'], '');
					}
					
					// we move the avatar to the proper folder
					if (is_dir($agora_avatar_dir) && is_file($agora_att_dir . DS . $ob['user_id'] . '.png')) {
						rename($agora_att_dir . DS . $ob['user_id'] . '.png', $agora_avatar_dir . DS . $ob['user_id'] . '.png');
					}
				
				}
				
			}
			
			$offset += QUERY_LIMIT;
			
		} while ($have_data);

		unset($ob_list);
		
		$this->db->setQuery('SELECT * FROM #__ccb_ranks');
		$ob_list = $this->db->loadAssocList();
		
		if (count($ob_list))
		foreach ($ob_list as $ob) {
			unset($todb);
			// Dataarray
			$todb = array(
				'id' => $ob['id'],
				'rank' => $ob['rank_title'],
				'min_posts' => $ob['rank_min'],
				'image' => $ob['rank_image'] 
			);
			//echo '<pre>'; print_r($todb); echo '</pre>';		        
			$this->_insertdata('ranks', $todb);
			
		}
	}

	function export_users_sforum() {
		$offset = 0;
		do {
			$have_data = false;		    
			$this->db->setQuery('SELECT * FROM #__users ORDER BY id LIMIT ' . $offset . ',' . QUERY_LIMIT);
			$ob_list = $this->db->loadAssocList();
			
			if (count($ob_list) > 0) {
				$have_data = true;
			}
			
			foreach ($ob_list as $ob) {
				//echo '<br>'.$ob['name'].' ('.$ob['id'].")\n"; flush();
				
				// Dataarray
				$todb = array(
					'id' => $ob['id'],
					'jos_id' => $ob['id'],
					'username' => $ob['username'],
					'email' => $ob['email'],
					'registered' => makeNewDateTime($ob['registerDate']),
				);
				
				//echo '<pre>'; print_r($todb); echo '</pre>';
				$this->_insertdata('users', $todb);
				
				//~ $ag_avatar='components/com_community/assets/default.jpg';
				//~ $ag_thumb='components/com_community/assets/default_thumb.jpg';
				
				//~ $com_users = array(
					//~ 'userid' => $ob['id'],
					//~ 'avatar' => $ag_avatar,
					//~ 'thumb' => $ag_thumb,
					//~ 'params' => _DEF_PARAMS
				//~ );
				
				//~ $this->_insertdata('community_users', $com_users, true);
				
			}
			
			$offset += QUERY_LIMIT;
			
		} while ($have_data);
	}
	
	function export_users_joobb() {
		$offset = 0;
		
		do {
			$have_data = false;
			$this->db->setQuery('SELECT * FROM #__joobb_users as cu LEFT JOIN #__users as u ON cu.id=u.id ORDER BY cu.id LIMIT ' . $offset . ',' . QUERY_LIMIT);
			$ob_list = $this->db->loadAssocList();
			
			if (count($ob_list) > 0) {
				$have_data = true;
			}
			
			foreach ($ob_list as $ob) {
				//echo '<br>'.$ob['name'].' ('.$ob['id'].")\n"; flush();
				
				$this->db->setQuery('SELECT date_post FROM #__joobb_posts WHERE id_user ='.$ob['id'].' ORDER BY date_post DESC LIMIT 1');
				$last_post = $this->db->loadResult();
				$this->db->setQuery('SELECT date_post FROM #__joobb_posts WHERE id_user ='.$ob['id'].' ORDER BY date_post ASC LIMIT 1');
				$registered = $this->db->loadResult();
				
				$this->db->setQuery('SELECT * FROM #__joocm_users as cmu LEFT JOIN #__joocm_profiles as cmp ON cmu.id=cmp.id LEFT JOIN #__joocm_avatars as cma ON cmu.id_avatar=cma.id WHERE cmu.id = '.$ob['id']);
				$cm_user = $this->db->loadAssoc();

				// Dataarray
				$todb = array(
					'id' => $ob['id'],
					'jos_id' => $ob['id'],
					'username' => $ob['username'],
					'email' => $ob['email'],
					'use_avatar ' => ($cm_user['id_avatar'] ? '1' : '0'),
					'num_posts' => $ob['posts'],
					'last_post' => makeNewDateTime($last_post),
					'registered' => makeNewDateTime($registered),
					'signature' => $cm_user['signature'] ,
					'location' => $cm_user['p_address'],
					'icq' => $cm_user['p_icq'],  
					'msn' => $cm_user['p_msnm'],  
				);
				//echo '<pre>'; print_r($todb); echo '</pre>';		        
				$this->_insertdata('users', $todb);
				
				$dir_ = dirname(dirname(dirname(dirname(__FILE__))));
				if ( !is_dir($dir_.'/components/com_agora/img/members/'.$ob['id']) )
				mkdir($dir_.'/components/com_agora/img/members/'.$ob['id']);
				
				if ($cm_user['id_avatar']) {
					if (is_file($dir_.'/media/joocm/avatars/standard/'.$cm_user['avatar_file']) && is_dir($dir_.'/components/com_agora/img/pre_avatars') )
					copy($dir_.'/media/joocm/avatars/standard/'.$cm_user['avatar_file'], $dir_.'/components/com_agora/img/pre_avatars/'.$ob['id'].'.png');
				} /*else {
					$ag_avatar='components/com_community/assets/default.jpg';
					$ag_thumb='components/com_community/assets/default_thumb.jpg';
				}*/
				
				//~ $com_users = array(
					//~ 'userid' => $ob['id'],
					//~ 'avatar' => $ag_avatar,
					//~ 'thumb' => $ag_thumb,
					//~ 'params' => _DEF_PARAMS
				//~ );
				
				//~ $this->_insertdata('community_users', $com_users, true);
				
			}
			
			$offset += QUERY_LIMIT;
			
		} while ($have_data);
	}
	
	function export_forums_kunena() {		    
		$pref = $this->kunena_prefix;
		
		$this->db->setQuery('SELECT * FROM #__' . $pref . '_categories ORDER BY id');
		$ob_list = $this->db->loadAssocList();
		
		foreach ($ob_list as $ob) {
			//echo '<br>'.$ob['name'].' ('.$ob['id'].")\n"; flush();
			
			// If parent is zero, it's a category
			if($ob['parent'] == 0) {
				$todb = array(
					'id' =>	$ob['id'],
					'cat_name' => $ob['name'],
					'disp_position' => $ob['ordering']
				);
				// Save data
				$this->_insertdata('categories', $todb);
			
			// Its a forum!
			} else{
				// Get last post information
				$this->db->setQuery('SELECT * FROM #__' . $pref . '_messages WHERE catid='.$ob['id'].' ORDER BY id DESC LIMIT 1');
				$post = $this->db->loadAssoc();

				// Get topic count
				$this->db->setQuery('SELECT count(*) FROM #__' . $pref . '_messages WHERE catid='.$ob['id'].' AND parent=0 ORDER BY id DESC LIMIT 1');
				list($num_topics) = $this->db->loadResult();
				$this->db->setQuery('SELECT count(*) FROM #__' . $pref . '_messages WHERE catid='.$ob['id'].' ORDER BY id DESC LIMIT 1');
				list($num_posts) = $this->db->loadResult();
				$this->db->setQuery('SELECT parent FROM #__' . $pref . '_categories WHERE id='.$ob['parent'].' LIMIT 1');
				$parent_parent = $this->db->loadResult();
				
				if($parent_parent==0) {
					$ob['cat_id'] = $ob['parent'];
					$ob['parent_forum_id'] = null;
				} else {
					while($parent_parent != 0) {
						$this->db->setQuery('SELECT parent FROM #__' . $pref . '_categories WHERE id='.$parent_parent.' LIMIT 1');					        					       
						$ob['cat_id']=$parent_parent;
						$parent_parent = $this->db->loadResult();
						if ($parent_parent == $ob['id']) break;
					 }
					$ob['parent_forum_id'] = $ob['parent'];
				}

				// Dataarray
				$todb = array(
					'id' =>		$ob['id'],
					'forum_name' => $ob['name'],
					'forum_desc' => $ob['description'],
					'moderators' => $ob['moderators'],
					'cat_id' => $ob['cat_id'],
					'parent_forum_id' => $ob['parent_forum_id'],
					'disp_position' => $ob['ordering'],
					'num_topics' => $num_topics,
					'num_posts' => $num_posts - $num_topics,
					'last_poster' => $post['name'],
					'last_post_id' => $post['id'],
					'last_post' => $post['time'],
				);
				
				$this->_insertdata('forums', $todb);
			}
			
		}	    			    
	}
	
	
	function export_forums_ccboard() {
	
		$this->db->setQuery('SELECT * FROM #__ccb_category ORDER BY id');
		$ob_list = $this->db->loadAssocList();

		foreach ($ob_list as $ob) {

			//echo '<br>'.$ob['name'].' ('.$ob['id'].")\n"; flush();
			
			$todb = array(
				'id'			=>	$ob['id'],
				'cat_name'		=> 	$ob['cat_name'],
				'disp_position'	=> 	$ob['ordering']
			);

			// Save data
			$this->_insertdata('categories', $todb);
		}
		unset($ob_list,$todb);
		
		$this->db->setQuery('SELECT f.*, u.username FROM #__ccb_forums AS f LEFT JOIN #__users as u ON u.id=f.last_post_user ORDER BY f.id');
		$ob_list = $this->db->loadAssocList();
		
		foreach ($ob_list as $ob) {		    
			// Dataarray
			$todb = array(
				'id' => $ob['id'],
				'forum_name' => $ob['forum_name'],
				'forum_desc' => $ob['forum_desc'],
				'moderators' => $ob['moderate_for'],
				'cat_id' => $ob['cat_id'],
				'parent_forum_id' => null,
				'disp_position' => $ob['ordering'],
				'num_topics' => $ob['topic_count'],
				'num_posts' => $ob['post_count'],
				'last_poster' => $ob['username'],
				'last_post_id' => $ob['last_post_id'],
				'last_post' => $ob['last_post_time'],
			);
			
			$this->_insertdata('forums', $todb);
		}
	}
	
	function export_forums_sforum() {		    
		
		$tocat = array(
			'id' => '1',
			'cat_name' => 'Global',
			'disp_position' =>  '1'
		);

		$this->_insertdata('categories', $tocat);		    
		
		$this->db->setQuery('SELECT * FROM #__simplestforum_forum ORDER BY id');
		$ob_list = $this->db->loadAssocList();

		foreach ($ob_list as $ob) {

			// Get last post information
			$this->db->setQuery('SELECT * FROM #__simplestforum_post WHERE forumId='.$ob['id'].' ORDER BY id DESC LIMIT 1');
			$post = $this->db->loadAssoc();
			$post['time'] = makeNewDateTime($post['date']);

			// Get topic count
			$this->db->setQuery('SELECT count(*) FROM #__simplestforum_post WHERE forumId='.$ob['id'].' AND parentId=0 ORDER BY id DESC LIMIT 1');
			list($num_topics) = $this->db->loadResult();
			$this->db->setQuery('SELECT count(*) FROM #__simplestforum_post WHERE forumId='.$ob['id'].' ORDER BY id DESC LIMIT 1');
			list($num_posts) = $this->db->loadResult();			        
			
			// Dataarray
			$todb = array(
				'id' => $ob['id'],
				'forum_name' => $ob['name'],
				'forum_desc' => $ob['description'],
				'moderators' => $ob['moderategid'],
				'cat_id' => '1',
				'parent_forum_id' => null,
				'disp_position' => $ob['ordering'],
				'num_topics' => $num_topics,
				'num_posts' => $num_posts - $num_topics,
				'last_poster' => $post['authorId'],
				'last_post_id' => $post['id'],
				'last_post' => $post['time'],
			);

			$this->_insertdata('forums', $todb);
		}
	}

	function export_forums_joobb() {		    
		$this->db->setQuery('SELECT * FROM #__joobb_categories ORDER BY id');
		$ob_list = $this->db->loadAssocList();
		
		foreach ($ob_list as $ob) {
			//echo '<br>'.$ob['name'].' ('.$ob['id'].")\n"; flush();
			
			$todb = array(
				'id' => $ob['id'],
				'cat_name' => $ob['name'],
				'disp_position' => $ob['ordering']
			);
			
			// Save data
			$this->_insertdata('categories', $todb);
		}
		unset($ob_list,$todb);
		
		$this->db->setQuery('SELECT * FROM #__joobb_forums ORDER BY id');
		$ob_list = $this->db->loadAssocList();

		foreach ($ob_list as $ob) {		    
			$this->db->setQuery('SELECT * FROM #__joobb_posts WHERE id='.$ob['id_last_post']);
			$post = $this->db->loadAssoc();
			$post['time'] = makeNewDateTime($post['date_post']);
			
			$user = & Model::getInstance('UserModel');
			$user_data_last_poster = $user->getJUser($post['id_user']);
				
			// Dataarray
			$todb = array(
				'id' => $ob['id'],
				'forum_name' => $ob['name'],
				'forum_desc' => $ob['description'],
				'moderators' => '',
				'cat_id' => $ob['id_cat'],
				'parent_forum_id' => null,
				'disp_position' => $ob['ordering'],
				'num_topics' => $ob['topics'],
				'num_posts' => $ob['posts'],
				'last_poster' => $user_data_last_poster['username'],
				'last_post_id' => $ob['id_last_post'],
				'last_post' => $post['time'],
			);

			$this->_insertdata('forums', $todb);
		}
	}
	
	
	function export_posts_kunena() {	
		$offset = 0;
		$pref = $this->kunena_prefix;
		
		do {
			$have_data = false;		
			$this->db->setQuery('SELECT * FROM #__' . $pref . '_messages AS m LEFT JOIN #__' . $pref . '_messages_text AS t ON t.mesid=m.id ORDER BY m.id LIMIT ' . $offset . ',' . QUERY_LIMIT);
			$ob_list = $this->db->loadAssocList();

			if (count($ob_list) > 0) {
				$have_data = true;
			}

			foreach ($ob_list as $ob) {
			
				//echo '<br>'.$ob['id'].' ('.$ob['name'].")\n"; flush();
				if($ob['parent'] == 0) {
				
					// Number of replies
					$this->db->setQuery('SELECT count(*) FROM #__' . $pref . '_messages WHERE thread='.$ob['id']);
					list($num_replies) = $this->db->loadResult();
					
					// Get last post information
					$this->db->setQuery('SELECT * FROM #__' . $pref . '_messages WHERE thread='.$ob['id'].' ORDER BY id DESC LIMIT 1');
					$post = $this->db->loadAssoc();
					unset($todb);
					
					// Dataarray
					$todb = array(
						'id' => $ob['thread'],
						'poster' => $ob['name'],
						'subject' => $ob['subject'],
						'posted' => $ob['time'],
						'forum_id' => $ob['catid'],
						'num_replies' => $num_replies - 1,
						'num_views' => $ob['hits'],
						'closed' => $ob['locked'],
						'sticky' => $ob['hold'],
						'last_post' => $post['time'],
						'last_post_id' => $post['id'],
						'last_poster' => $post['name'],
					);

					$this->_insertdata('topics', $todb);
				}
				$this->db->setQuery('SELECT * FROM #__' . $pref . '_messages AS m JOIN #__' . $pref . '_attachments as A ON A.mesid=m.id WHERE m.id='.$ob['id']);
				$attachs = $this->db->loadAssocList();
				
				foreach ($attachs as $r_attachs) {
				
					$kunena_att_dir = JPATH_ROOT . DS . $r_attachs['folder'];
					$kunena_att_file = JPATH_ROOT . DS . $r_attachs['folder'] . DS . $r_attachs['filename'];
				
					$agora_att_dir = JPATH_ROOT . DS . 'components' . DS . 'com_agora' . DS . 'img' . DS . 'members';
					if (!is_dir($agora_att_dir)) mkdir($agora_att_dir);
					$agora_att_dir = JPATH_ROOT . DS . 'components' . DS . 'com_agora' . DS . 'img' . DS . 'members' . DS . $r_attachs['userid'];
					if (!is_dir($agora_att_dir)) mkdir($agora_att_dir);
					
					$agora_filename = $this->upload_model->_parse_file(substr($r_attachs['filename'], 0, strpos($r_attachs['filename'], '.'))) . substr($r_attachs['filename'], strpos($r_attachs['filename'], '.'));
					$agora_att_file = $agora_att_dir . DS . $agora_filename;
					$agora_att_file_mini = $agora_att_dir . DS . 'mini_' . $agora_filename;

					$agora_web_dir = Agora::getSite() . 'img/members/' . $r_attachs['userid'];
					$agora_web_file = $agora_web_dir . '/' . $agora_filename;
					$agora_web_mini = $agora_web_dir . '/mini_' . $agora_filename;

					copy($kunena_att_file, $agora_att_file);
					
					if (is_file($agora_att_file)) {
					
						if (strpos($r_attachs['filetype'], 'image') !== false) { // image attachment
							$this->upload_model->makeThumb($r_attachs['userid'], $agora_filename, $this->agora_config['o_uploadile_thumb_size']);
							$this->upload_model->makeThumb($r_attachs['userid'], $agora_filename, $this->agora_config['o_uploadile_disp_size'], '');
							$agora_web_mini = (is_file($agora_att_file_mini) && @getimagesize($agora_att_file_mini)) ? $agora_web_mini : $agora_web_file;
							$to_find = '[attachment=' . $r_attachs['id'] . ']' . $r_attachs['filename'] . '[/attachment]';
							$to_replace = '[url=' . $agora_web_file . '][img]' . $agora_web_mini . '[/img][/url]';
						} else { // other attachment
							$to_find = '[attachment=' . $r_attachs['id'] . ']' . $r_attachs['filename'] . '[/attachment]';
							$to_replace = '[url=' . $agora_web_file . ']##text##[/url]';
						}
						
						if (strpos($ob['message'], $to_find) !== false ) {
							$ob['message'] = str_replace($to_find, $to_replace, $ob['message']);
						} else {
							$ob['message'] = $ob['message'] . "\n" . $to_replace;
						}
						
					}
				}
				
				$ob['message'] = convert_posts($ob['message']);
				
				unset($todb);
				
				$todb = array(
					'id' => $ob['id'],
					'poster' => $ob['name'],
					'poster_id' => $ob['userid'],
					'posted' => $ob['time'],
					'poster_ip' => $ob['ip'],
					'message' => $ob['message'],
					'topic_id' => $ob['thread']
				);
				
				$this->_insertdata('posts', $todb);
			}
			
			$offset += QUERY_LIMIT;
			
		} while ($have_data);
		
	}

	function export_subscriptions_kunena() {	
		$pref = $this->kunena_prefix;
		
		$sql = 'INSERT INTO #__agora_subscriptions (`user_id`, `topic_id`) SELECT `userid`, `thread` FROM  #__' . $pref . '_subscriptions';
		$this->db->setQuery($sql);
		$this->db->query();
	}

	function export_posts_ccboard() {	
		$offset = 0;
		
		$ccboard_att_dir = JPATH_ROOT . DS . 'components' . DS . 'com_ccboard' . DS . 'assets' . DS . 'uploads';
		
		do {
			$have_data = false;		
			$this->db->setQuery('SELECT t.*, u.username, uu.username as topic_starter FROM #__ccb_topics as t LEFT JOIN #__users as u ON u.id=t.last_post_user LEFT JOIN #__users as uu ON uu.id=t.post_user ORDER BY t.id LIMIT ' . $offset . ',' . QUERY_LIMIT);
			$ob_list = $this->db->loadAssocList();

			if (count($ob_list) > 0) {
				$have_data = true;
			}

			foreach ($ob_list as $ob) {

				//echo '<br>'.$ob['id'].' ('.$ob['post_subject'].")\n"; flush();
			
				// Dataarray
				$todb = array(
					'id' => $ob['id'],
					'poster' => $ob['topic_starter'],
					'subject' => $ob['post_subject'],
					'posted' => $ob['post_time'],
					'forum_id' => $ob['forum_id'],
					'num_replies' => $ob['reply_count'],
					'num_views' => $ob['hits'],
					'closed' => $ob['locked'],
					'sticky' => $ob['hold'],
					'last_post' => $ob['last_post_time'],
					'last_post_id' => $ob['last_post_id'],
					'last_poster' => $ob['username'],
				);
				
				$this->_insertdata('topics', $todb);
			}
		
			unset($ob_list,$todb);
			
			$this->db->setQuery('SELECT p.*, u.username FROM #__ccb_posts as p LEFT JOIN #__users as u ON u.id=p.post_user ORDER BY p.id LIMIT ' . $offset . ',' . QUERY_LIMIT);
			$ob_list = $this->db->loadAssocList();

			if (count($ob_list) > 0) {
				$have_data = true;
			}
			
			foreach ($ob_list as $ob) {
			
					$ob['post_text'] = ccboard_html2bbcode($ob['post_text']);
					
					$this->db->setQuery('SELECT * FROM #__ccb_posts AS m LEFT JOIN #__ccb_attachments as A ON A.post_id=m.id WHERE m.id='.$ob['id'].' AND not isnull(A.ccb_name)');
					$attachs = $this->db->loadAssocList();
					
					foreach ($attachs as $r_attachs) {
					
						$ccboard_att_file = $ccboard_att_dir . DS . $r_attachs['ccb_name'];
					
						$agora_att_dir = JPATH_ROOT . DS . 'components' . DS . 'com_agora' . DS . 'img' . DS . 'members';
						if (!is_dir($agora_att_dir)) mkdir($agora_att_dir);
						$agora_att_dir = JPATH_ROOT . DS . 'components' . DS . 'com_agora' . DS . 'img' . DS . 'members' . DS . $r_attachs['post_user'];
						if (!is_dir($agora_att_dir)) mkdir($agora_att_dir);
						
						$agora_filename = $this->upload_model->_parse_file(substr($r_attachs['real_name'], 0, strpos($r_attachs['real_name'], '.'))) . strtolower(substr($r_attachs['real_name'], strpos($r_attachs['real_name'], '.')));
						$agora_att_file = $agora_att_dir . DS . $agora_filename;
						$agora_att_file_mini = $agora_att_dir . DS . 'mini_' . $agora_filename;

						$agora_web_dir = Agora::getSite() . 'img/members/' . $r_attachs['post_user'];
						$agora_web_file = $agora_web_dir . '/' . $agora_filename;
						$agora_web_mini = $agora_web_dir . '/mini_' . $agora_filename;

						copy($ccboard_att_file, $agora_att_file);
						
						if (is_file($agora_att_file)) {
						
							if (@getimagesize($agora_att_file)) { //image attachment
								$this->upload_model->makeThumb($r_attachs['post_user'], $agora_filename, $this->agora_config['o_uploadile_thumb_size']);
								$this->upload_model->makeThumb($r_attachs['post_user'], $agora_filename, $this->agora_config['o_uploadile_disp_size'], '');
								$agora_web_mini = (is_file($agora_att_file_mini) && @getimagesize($agora_att_file_mini)) ? $agora_web_mini : $agora_web_file;
								$att_code = '[url=' . $agora_web_file . '][img]' . $agora_web_mini . '[/img][/url]';
							} else { // other attachment
								$att_code = '[url=' . $agora_web_file . ']##text##[/url]';
							}
						
							$ob['post_text'] .= "\n" . $att_code;
						}
					}


					$todb = array(
						'id' => $ob['id'],
						'poster' => $ob['username'],
						'poster_id' => $ob['post_user'],
						'posted' => $ob['post_time'],
						'poster_ip' => $ob['ip'],
						'message' => $ob['post_text'],
						'topic_id' => $ob['topic_id']
					);
		
					$this->_insertdata('posts', $todb);		       
			}
			
			$offset += QUERY_LIMIT;
			
		} while ($have_data);		
	}
	
	function export_posts_sforum() {
		$offset = 0;
		
		do {
			$have_data = false;
			$this->db->setQuery('SELECT * FROM #__simplestforum_post ORDER BY id LIMIT ' . $offset . ',' . QUERY_LIMIT);
			$ob_list = $this->db->loadAssocList();

			if (count($ob_list) > 0) {
				$have_data = true;
			}

			foreach ($ob_list as $ob) {
				$user = & Model::getInstance('UserModel');
				$user_data_last_poster = $user->getJUser($post['authorId']);
				$user_data = $user->getJUser($ob['authorId']);
				//echo '<br>'.$ob['id'].' ('.$ob['authorId'].")\n"; flush();
				
				if($ob['parentId'] == 0) {
					// Number of replies
					$this->db->setQuery('SELECT count(*) FROM #__simplestforum_post WHERE thread='.$ob['id']);
					list($num_replies) = $this->db->loadResult();
					// Get last post information
					$this->db->setQuery('SELECT * FROM #__simplestforum_post WHERE thread='.$ob['id'].' ORDER BY id DESC LIMIT 1');
					$post = $this->db->loadAssoc();
			
					// Dataarray
					$todb = array(
						'id' => $ob['thread'],
						'poster' => $user_data['username'],
						'subject' => $ob['subject'],
						'posted' => makeNewDateTime($ob['date']),
						'forum_id' => $ob['forumId'],
						'num_replies' => $num_replies - 1,
						'num_views' => 0,
						'closed' => $ob['published'],
						'last_post' => makeNewDateTime($post['date']),
						'last_post_id' => $post['id'],
						'last_poster' => $user_data_last_poster['username'],
					);

					$this->_insertdata('topics', $todb);
					
				}
				unset($todb);
				
				$todb = array(
					'id' => $ob['id'],
					'poster' => $user_data['username'],
					'poster_id' => $ob['authorId'],
					'posted' => makeNewDateTime($ob['date']),
					'poster_ip' => $ob['authorIP'],
					'message' => $ob['message'],
					'topic_id' => $ob['thread']
				);
				
				$this->_insertdata('posts', $todb);		       
			}
			
			$offset += QUERY_LIMIT;
			
		} while ($have_data);
		
	}
	
	function export_posts_joobb() {
		$offset = 0;
		
		do {
			$have_data = false;		
			$this->db->setQuery('SELECT * FROM #__joobb_topics as jt LEFT JOIN #__joobb_posts as jp ON jp.id=jt.id_first_post ORDER BY jt.id LIMIT ' . $offset . ',' . QUERY_LIMIT);
			$ob_list = $this->db->loadAssocList();

			if (count($ob_list) > 0) {
				$have_data = true;
			}

			foreach ($ob_list as $ob) {
				$user = & Model::getInstance('UserModel');
				$user_data = $user->getJUser($ob['id_user']);
				$this->db->setQuery('SELECT * FROM #__joobb_posts WHERE id='.$ob['id_last_post']);
				$lpost = $this->db->loadAssoc();
				$user_lp = $user->getJUser($lpost['id_user']);
								
				$last_id = $ob['id'];
				//echo '<br>'.$ob['id'].' ('.$ob['post_subject'].")\n"; flush();
			
				// Dataarray
				$todb = array(
					'id' => $ob['id'],
					'poster' => $user_data['username'],
					'subject' => $ob['subject'],
					'posted' => makeNewDateTime($ob['date_post']),
					'forum_id' => $ob['id_forum'],
					'num_replies' => $ob['replies'],
					'num_views' => $ob['views'],
					'closed' => '0',
					'sticky' => '0',
					'last_post' => makeNewDateTime($lpost['date_post']),
					'last_post_id' => $ob['id_last_post'],
					'last_poster' => $user_lp['username'],
				);

				$this->_insertdata('topics', $todb);
			}
			
			unset($ob_list,$todb,$user_data);
			$this->db->setQuery('SELECT * FROM #__joobb_posts ORDER BY id LIMIT ' . $offset . ',' . QUERY_LIMIT);
			$ob_list = $this->db->loadAssocList();

			if (count($ob_list) > 0) {
				$have_data = true;
			}

			foreach ($ob_list as $ob) {
				$user = & Model::getInstance('UserModel');
				$user_data = $user->getJUser($ob['id_user']);
				
				$this->db->setQuery('SELECT * FROM #__joobb_posts AS m LEFT JOIN #__joobb_attachments as A ON A.id_post=m.id WHERE m.id='.$ob['id'].' AND not isnull(A.file_name)');
				$attachs = $this->db->loadAssocList();
				
				foreach ($attachs as $r_attachs) {
					$upload_dir = dirname(dirname(dirname(dirname(__FILE__)))).'/components/com_agora/img/members/'.$ob['id_user'];			            
					$file = dirname(dirname(dirname(dirname(__FILE__)))).'/media/joobb/attachments/'.$r_attachs['file_name'];
					if (!is_dir($upload_dir)) mkdir($upload_dir);
					copy( $file, $upload_dir.'/'.$r_attachs['original_name'] );
					$uri =& JURI::getInstance();
					$ob['text'] .= '[url]'.$uri->root().'components/com_agora/img/members/'.$ob['id_user'].'/'.$r_attachs['original_name'].'[/url]';
				}
				$todb = array(
					'id' => $ob['id'],
					'poster' => $user_data['username'],
					'poster_id' => $ob['id_user'],
					'posted' => makeNewDateTime($ob['date_post']),
					'poster_ip' => $ob['ip_poster'],
					'message' => $ob['text'],
					'topic_id' => $ob['id_topic']
				);
				
				$this->_insertdata('posts', $todb);
			}
			
			$offset += QUERY_LIMIT;
			
		} while ($have_data);
		
	}
	
	protected function _truncate_tables($forum) {
		$truncates = array();
		$truncates[] = 'TRUNCATE TABLE ##__categories';
		$truncates[] = 'TRUNCATE TABLE ##__censoring';
		$truncates[] = 'TRUNCATE TABLE ##__posts';
		$truncates[] = 'TRUNCATE TABLE ##__forums';
		$truncates[] = 'TRUNCATE TABLE ##__ranks';
		$truncates[] = 'TRUNCATE TABLE ##__topics';
		$truncates[] = 'TRUNCATE TABLE ##__users';
		// DO NOT MESS WITH JOMSOCIAL - ARE YOU CRAZY VICTOR?
		//$truncates[] = 'TRUNCATE TABLE #__community_users';
		$truncates[] = 'TRUNCATE TABLE ##__bans';
		$truncates[] = 'TRUNCATE TABLE ##__subscriptions';
		$truncates[] = 'TRUNCATE TABLE ##__bans_auto';
		$truncates[] = 'TRUNCATE TABLE ##__polls'; // AgoraPoll
		$truncates[] = 'TRUNCATE TABLE ##__messages'; // AgoraPMS		
		//$truncates[] = 'TRUNCATE TABLE #__users';
		//$truncates[] = 'TRUNCATE TABLE #__core_acl_aro';
		//$truncates[] = 'TRUNCATE TABLE #__core_acl_groups_aro_map';
		@reset($truncates);		    
		while(list( ,$sql) = @each($truncates)) {
			$this->setQuery($sql);
			$this->db->query();
		}
	}

	protected function _remove_indexes($forum) {
		
		$queries[] = 'ALTER TABLE #__agora_forums DROP INDEX enable';
		$queries[] = 'ALTER TABLE #__agora_forums DROP INDEX last_post';
		$queries[] = 'ALTER TABLE #__agora_forums DROP INDEX #__agora_forums_lastpostid_index';	
		$queries[] = 'ALTER TABLE #__agora_posts DROP INDEX #__agora_posts_posts_posted_idx';
		$queries[] = 'ALTER TABLE #__agora_posts DROP INDEX #__agora_posts_topic_id_idx';
		$queries[] = 'ALTER TABLE #__agora_posts DROP INDEX #__agora_posts_multi_idx';
		$queries[] = 'ALTER TABLE #__agora_reports DROP INDEX #__agora_reports_zapped_idx';
		$queries[] = 'ALTER TABLE #__agora_topics DROP INDEX #__agora_topics_forum_id_idx';
		$queries[] = 'ALTER TABLE #__agora_topics DROP INDEX #__agora_topics_moved_to_idx';
		$queries[] = 'ALTER TABLE #__agora_topics DROP INDEX #__agora_topics_lastpostid_index';
		$queries[] = 'ALTER TABLE #__agora_users DROP INDEX #__id_index';
		$queries[] = 'ALTER TABLE #__agora_users DROP INDEX #__agora_users_num_posts_idx';
		$queries[] = 'ALTER TABLE #__agora_users DROP INDEX #__agora_users_registered_idx';
		$queries[] = 'ALTER TABLE #__agora_users DROP INDEX #__agora_users_username_idx';
		$queries[] = 'ALTER TABLE #__agora_user_group DROP INDEX user_id';

		@reset($queries);
		while (list(, $sql) = @each($queries)) {
			$this->setQuery($sql);
			$this->db->query();
		}		    		    
	}
	
	protected function _add_indexes() {
		
		$queries[] = 'ALTER TABLE #__agora_forums ADD INDEX enable(enable)';
		$queries[] = 'ALTER TABLE #__agora_forums ADD INDEX last_post(last_post)';
		$queries[] = 'ALTER TABLE #__agora_forums ADD INDEX #__agora_forums_lastpostid_index(last_post_id)';	
		$queries[] = 'ALTER TABLE #__agora_posts ADD INDEX #__agora_posts_posted_idx(posted)';
		$queries[] = 'ALTER TABLE #__agora_posts ADD INDEX #__agora_posts_topic_id_idx(topic_id)';
		$queries[] = 'ALTER TABLE #__agora_posts ADD INDEX #__agora_posts_multi_idx(poster_id, topic_id)';
		$queries[] = 'ALTER TABLE #__agora_reports ADD INDEX #__agora_reports_zapped_idx(zapped)';
		$queries[] = 'ALTER TABLE #__agora_topics ADD INDEX #__agora_topics_forum_id_idx(forum_id)';
		$queries[] = 'ALTER TABLE #__agora_topics ADD INDEX #__agora_topics_moved_to_idx(moved_to)';
		$queries[] = 'ALTER TABLE #__agora_topics ADD INDEX #__agora_topics_lastpostid_index';
		$queries[] = 'ALTER TABLE #__agora_users ADD INDEX #__id_index(jos_id)';
		$queries[] = 'ALTER TABLE #__agora_users ADD INDEX #__agora_users_num_posts_idx(num_posts)';
		$queries[] = 'ALTER TABLE #__agora_users ADD INDEX #__agora_users_registered_idx(registered)';
		$queries[] = 'ALTER TABLE #__agora_users ADD INDEX #__agora_users_username_idx(username(8))';
		$queries[] = 'ALTER TABLE #__agora_user_group ADD INDEX user_id(user_id, group_id)';

		@reset($queries);
		while (list(, $sql) = @each($queries)) {
			$this->setQuery($sql);
			$this->db->query();
		}

	}


	protected function _recount() {
		$this->db->setQuery('UPDATE #__agora_topics SET num_replies = 
							(select count(*)-1 from #__agora_posts 
							WHERE topic_id=#__agora_topics.id)');
		$this->db->query();
		$this->db->setQuery('UPDATE #__agora_forums SET
							num_topics = (select count(*) from #__agora_topics 
							WHERE forum_id=#__agora_forums.id), num_posts = COALESCE((select sum(num_replies) 
							FROM #__agora_topics WHERE forum_id = #__agora_forums.id),0)');
		$this->db->query();
		$this->db->setQuery('UPDATE #__agora_users SET num_posts = 
							(select count(*) from #__agora_posts 
							WHERE poster_id=#__agora_users.id)');
		$this->db->query();

	}
	
	
	protected function _insertdata($table, $todb, $todb_pref_flag='') { 

		// Put together the query
		$names = array();
		$vars = array();

		foreach($todb as $name => $var) {
			if ($var != '') {
				$names[] = $name;
				$var == 'null' ? $vars[] = $var : $vars[] = '\''.addslashes(stripslashes(html($var))).'\'';
			}
		}
		if ($todb_pref_flag)
		$query = 'INSERT INTO #__'.$table.' ('.implode(',', $names).') VALUES('.implode(',', $vars).')';
		else 
		$query = 'INSERT INTO ##__'.$table.' ('.implode(',', $names).') VALUES('.implode(',', $vars).')';		
		$this->setQuery($query);
		$this->db->query();
			
		return $this->db->insertid();
	}
	
}
	
function html($message) {		
	$pattern = array(
	'/&gt;/i',
	'/&lt;/i',
	'/&amp;/i',
	'/&quot;/i',
	'/&#039;/i'
	);

	$replace = array(
	'>',
	'<',
	'&',
	'"',
	"'"
	);
	
    return preg_replace($pattern, $replace, $message);		
}

function convert_posts($message) {
	$pattern = array(
		'#\[img size=(.*?)\](.*?)\[/img\]#i',
		'#\[strike\](.*?)\[/strike\]#i',
	);
	
	$replace = array(
		'[img width=$1]$2[/img]',
		'[s]$1[/s]',
	);

	return preg_replace($pattern, $replace, $message);
}

function makeNewDateTime($datetime) {
	    
	$year = substr($datetime,0,4);
	$month = substr($datetime,5,2);
	$day = substr($datetime,8,2);
	$hour = substr($datetime,11,2);
	$min = substr($datetime,14,2);
	$sec = substr($datetime,17,2);

	return mktime($hour,$min,$sec,$month,$day,$year);
}

function ccboard_html2bbcode($text) {

	$pregfind = array(
		
		// Smilies
		'#>:\(#i',
		'#\^_\^#i',
		'#8\)#i',
		'#:-D#i',
		'#;D#i',
		'#o\.O#i',
		'#B-\)#i',
		'#>:\)#i',
		'#<3#i',
		'#:-/#i',
		'#X-D#i',
		'#O:\)#i',
		'#:-3#i',
		'#>;\)#i',
		'#<g>#i',
		'#:-S#i',
		
		// html
		"/<script.*>.*<\/script>/siU",
		'/on(mousewheel|mouseover|click|load|onload|submit|focus|blur)="[^"]*"/i',
		"/<table([^>]*(width|background|background-color|bgcolor)[^>]*)>/siUe",
		"/<table.*>/siU",
		"/<tr.*>/siU",
		"/<td>/i",
		"/<td(.+)>/siUe",
		"/<\/td>/i",
		"/<\/tr>/i",
		"/<\/table>/i",
		"/<img[^>]+smilieid=\"(\d+)\".*>/esiU",
		"/<img([^>]*src[^>]*)>/eiU",
		"/<a\s+?name=.+?\".\">(.+?)<\/a>/is",
		"/<br.*>/siU",
		"/<span\s+?style=\"float:\s+(left|right);\">(.+?)<\/span>/is",
		"/<ul>/i",
		"/<\/ul>/i",
		"/<ol>/i",
		"/<\/ol>/i",
		"/<li>/i",
		"/<\/li>/i",
		
		// sizes
		'#\[size=0\]#i',
		'#\[size=1\]#i',
		'#\[size=2\]#i',
		'#\[size=3\]#i',
		'#\[size=4\]#i',
		'#\[size=5\]#i',
		'#\[size=6\]#i',
		'#\[size=7\]#i',
		'#\[/size\]#i',
		
		// lists
		'#\[list=(.*?)\](.*?)\[/list\]#is',
		'#\[list\](.*?)\[/list\]#is',
		'#\[\*\](.*?)\[#i',
		'#\[\*\](.*?)\[#i',
		'#\[\*\](.*)#i',

	);
	$pregreplace = array(
		
		// Smilies
		':mad:',
		':)',
		':)',
		':D',
		';)',
		':rolleyes:',
		':cool:',
		':)',
		':heart:',
		':/',
		':lol:',
		':)',
		':)',
		';)',
		':D',
		':/',
		
		// html
		'',
		'',
		"[table]",
		'[table]',
		'[tr]',
		'[td]',
		"[td]",
		'[/td]',
		'[/tr]',
		'[/table]',
		"[size=\\1]\\2[/size]\n\n",
		"imgtag('\\1')",
		'\1',
		"\n",
		"[float=\\1]\\2[/float]",
		"[ul]",
		"[/ul]",
		"[ol]",
		"[/ol]",
		"[li]",
		"[/li]",
		
		// sizes
		'[size=8]',
		'[size=8]',
		'[size=10]',
		'[size=12]',
		'[size=14]',
		'[size=18]',
		'[size=24]',
		'[size=36]',
		'[/size]',

		// Lists
		'[ol]$2[/ol]',
		'[ul]$1[/ul]',
		"[*]$1\n[",
		"[*]$1\n[",
		'[li]$1[/li]',
	);
	$text = preg_replace($pregfind, $pregreplace, $text);

	$text = recursion('b', $text, 'simpletag', 'b');
	$text = recursion('strong', $text, 'simpletag', 'b');
	$text = recursion('i', $text, 'simpletag', 'i');
	$text = recursion('em', $text, 'simpletag', 'i');
	$text = recursion('u', $text, 'simpletag', 'u');
	$text = recursion('a', $text, 'atag');
	$text = recursion('font', $text, 'fonttag');
	$text = recursion('blockquote', $text, 'simpletag', 'indent');
	$text = recursion('ol', $text, 'listtag');
	$text = recursion('ul', $text, 'listtag');
	$text = recursion('div', $text, 'divtag');
	$text = recursion('span', $text, 'spantag');
	$text = recursion('p', $text, 'ptag');

	$pregfind = array("/(?<!\r|\n|^)\[(\/list|list|\*)\]/", "/<li>(.*)((?=<li>)|<\/li>)/iU", "/<p.*>/iU", "/<p><\/p>/i", "/(<a>|<\/a>|<\/li>)/is", "/<\/?(A|LI|FONT|DIV|SPAN)>/siU", "/\[url[^\]]*\]\[\/url\]/i", "/\[url=javascript:[^\]]*\](.+?)\[\/url\]/is");
	$pregreplace = array("\n[\\1]", "\\1\n", "\n", '', '', '', '', "\\1");
	$text = preg_replace($pregfind, $pregreplace, $text);

	$text = strip_tags($text);

	$strfind = array('&nbsp;', '&lt;', '&gt;', '&amp;');
	$strreplace = array(' ', '<', '>', '&');
	$text = str_replace($strfind, $strreplace, $text);

	return trim($text);
}

function getoptionvalue($option, $text) {
	preg_match("/$option(\s+?)?\=(\s+?)?[\"']?(.+?)([\"']|$|>)/is", $text, $matches);
	if (isset($matches[3]))
	return trim($matches[3]);
	else
	return '';
}

function parsestyle($tagoptions, &$prependtags, &$appendtags) {
	$searchlist = array(
		//~ array('tag' => 'align', 'option' => TRUE, 'regex' => 'text-align:\s*(left);?', 'match' => 1),
		//~ array('tag' => 'align', 'option' => TRUE, 'regex' => 'text-align:\s*(center);?', 'match' => 1),
		//~ array('tag' => 'align', 'option' => TRUE, 'regex' => 'text-align:\s*(right);?', 'match' => 1),
		array('tag' => 'color', 'option' => TRUE, 'regex' => '(?<![a-z0-9-])color:\s*([^;]+);?', 'match' => 1),
		array('tag' => 'font', 'option' => TRUE, 'regex' => 'font-family:\s*([^;]+);?', 'match' => 1),
		array('tag' => 'size', 'option' => TRUE, 'regex' => 'font-size:\s*(\d+(\.\d+)?(px|pt|in|cm|mm|pc|em|ex|%|));?', 'match' => 1),
		array('tag' => 'b', 'option' => FALSE, 'regex' => 'font-weight:\s*(bold);?'),
		array('tag' => 'i', 'option' => FALSE, 'regex' => 'font-style:\s*(italic);?'),
		array('tag' => 'u', 'option' => FALSE, 'regex' => 'text-decoration:\s*(underline);?'),
		array('tag' => 's', 'option' => FALSE, 'regex' => 'text-decoration:\s*(line-through);?')
	);

	$style = getoptionvalue('style', $tagoptions);
	$style = preg_replace(
		"/(?<![a-z0-9-])color:\s*rgb\((\d+),\s*(\d+),\s*(\d+)\)(;?)/ie",
		'sprintf("color: #%02X%02X%02X$4", $1, $2, $3)',
		$style
	);
	foreach($searchlist as $searchtag) {
		if(preg_match('/'.$searchtag['regex'].'/i', $style, $match)) {
		    if ( isset($match)){
		        $ii = $searchtag.'[match]';
		        if (isset($match[$ii]))
			    $opnvalue = $match["$searchtag[match]"];
			    else $opnvalue = '';
		    }
			else
			$opnvalue = '';
			
			$prependtags .= '['.$searchtag['tag'].($searchtag['option'] == TRUE ? '='.$opnvalue.']' : ']');
			$appendtags = '[/'.$searchtag['tag']."]$appendtags";
		}
	}
}

function simpletag($options, $text, $tagname, $parseto) {
	if(trim($text) == '') {
		return '';
	}
	$text = recursion($tagname, $text, 'simpletag', $parseto);
	return "[$parseto]{$text}[/$parseto]";
}

function spantag($spanoptions, $text) {
	$prependtags = $appendtags = '';
	parsestyle($spanoptions, $prependtags, $appendtags);

	return $prependtags.recursion('span', $text, 'spantag').$appendtags;
}

function atag($aoptions, $text) {
	$href = getoptionvalue('href', $aoptions);

	if(substr($href, 0, 7) == 'mailto:') {
		$tag = 'email';
		$href = substr($href, 7);
	} else {
		$tag = 'url';
		if(!preg_match("/^[a-z0-9]+:/i", $href)) {
		    $uri =& JURI::getInstance();
			$href = $uri->root().$href;
		}
	}

	return "[$tag=$href]".trim(recursion('a', $text, 'atag'))."[/$tag]";
}

function litag($listoptions, $text) {
	return '[*]'.rtrim($text);
}

function listtag($listoptions, $text, $tagname) {

	$text = preg_replace('/<li>((.(?!<\/li))*)(?=<\/?ol|<\/?ul|<li|\[list|\[\/list)/siU', '<li>\\1</li>', $text);
	$text = recursion('li', $text, 'litag');

	if($tagname == 'ol') {
		$listtype = fetchoptionvalue('type=', $listoptions) ? fetchoptionvalue('type=', $listoptions) : 1;
		if(in_array($listtype, array('1', 'a', 'A'))) {
			$opentag = '[list='.$listtype.']';
		}
	} else {
		$opentag = '[list]';
	}
	return $text ? $opentag.recursion($tagname, $text, 'listtag').'[/list]' : FALSE;
}


function fetchoptionvalue($option, $text) {
	if(($position = strpos($text, $option)) !== false) {
		$delimiter = $position + strlen($option);
		if($text{$delimiter} == '"') {
			$delimchar = '"';
		} elseif($text{$delimiter} == '\'') {
			$delimchar = '\'';
		} else {
			$delimchar = ' ';
		}
		$delimloc = strpos($text, $delimchar, $delimiter + 1);
		if($delimloc === false) {
			$delimloc = strlen($text);
		} elseif($delimchar == '"' OR $delimchar == '\'') {
			$delimiter++;
		}
		return trim(substr($text, $delimiter, $delimloc - $delimiter));
	} else {
		return '';
	}
}

function fonttag($fontoptions, $text) {
	$tags = array('font' => 'face=', 'size' => 'size=', 'color' => 'color=');
	$prependtags = $appendtags = '';

	foreach($tags as $bbcode => $locate) {
		$optionvalue = fetchoptionvalue($locate, $fontoptions);
		if($optionvalue) {
			$prependtags .= "[$bbcode=$optionvalue]";
			$appendtags = "[/$bbcode]$appendtags";
		}
	}

	parsestyle($fontoptions, $prependtags, $appendtags);

	return $prependtags.recursion('font', $text, 'fonttag').$appendtags;
}


function divtag($divoptions, $text) {
	$prepend = $append = '';

	parsestyle($divoptions, $prepend, $append);
	$align = getoptionvalue('style', $divoptions);
	$align = trim(str_replace(array('text-align:',';'), array('' ,''), $align));

	switch($align) {
		case 'left':
		case 'center':
		case 'right':
		case 'justify':
			break;
		default:
			$align = '';
	}

	if($align) {
		$prepend .= "[$align]";
		$append .= "[/$align]";
	}
	$append .= "\n";

	return $prepend.recursion('div', $text, 'divtag').$append;
}

function imgtag($attributes) {
	$value = array('src' => '', 'width' => '', 'height' => '');
	preg_match_all("/(src|width|height)=([\"|\']?)([^\"']+)(\\2)/is", stripslashes($attributes), $matches);
	if(is_array($matches[1])) {
		foreach($matches[1] as $key => $attribute) {
			$value[strtolower($attribute)] = $matches[3][$key];
		}
	}
	@extract($value);
	if(!preg_match("/^http:\/\//i", $src)) {
	    $uri =& JURI::getInstance();
		$src = $uri->root().$src;
	}
	return $src ? ($width && $height ? '[img='.$width.','.$height.']'.$src.'[/img]' : '[img]'.$src.'[/img]') : '';
}


function ptag($poptions, $text) {
	
	$align = getoptionvalue('style', $poptions);
	$align = trim(str_replace(array('text-align:',';'), array('' ,''), $align));
	switch($align) {
		case 'left':
		case 'center':
		case 'right':
		case 'justify':
			break;
		default:
			$align = '';
	}

	$prepend = $append = '';
	parsestyle($poptions, $prepend, $append);
	if($align) {
		$prepend .= "[$align]";
		$append .= "[/$align]";
	}
	$append .= "\n";

	return $prepend.recursion('p', $text, 'ptag').$append;
}

function recursion($tagname, $text, $function, $extraargs = '') {
	$tagname = strtolower($tagname);
	$open_tag = "<$tagname";
	$open_tag_len = strlen($open_tag);
	$close_tag = "</$tagname>";
	$close_tag_len = strlen($close_tag);

	$beginsearchpos = 0;
	do {
		$textlower = strtolower($text);
		$tagbegin = @strpos($textlower, $open_tag, $beginsearchpos);
		if($tagbegin === FALSE) {
			break;
		}

		$strlen = strlen($text);

		$inquote = '';
		$found = FALSE;
		$tagnameend = FALSE;
		for($optionend = $tagbegin; $optionend <= $strlen; $optionend++) {
			$char = $text{$optionend};
			if(($char == '"' || $char == "'") && $inquote == '') {
				$inquote = $char;
			} elseif(($char == '"' || $char == "'") && $inquote == $char) {
				$inquote = '';
			} elseif($char == '>' && !$inquote) {
				$found = TRUE;
				break;
			} elseif(($char == '=' || $char == ' ') && !$tagnameend) {
				$tagnameend = $optionend;
			}
		}
		if(!$found) {
			break;
		}
		if(!$tagnameend) {
			$tagnameend = $optionend;
		}
		$offset = $optionend - ($tagbegin + $open_tag_len);
		$tagoptions = substr($text, $tagbegin + $open_tag_len, $offset);
		$acttagname = substr($textlower, $tagbegin + 1, $tagnameend - $tagbegin - 1);
		if($acttagname != $tagname) {
			$beginsearchpos = $optionend;
			continue;
		}

		$tagend = strpos($textlower, $close_tag, $optionend);
		if($tagend === FALSE) {
			break;
		}

		$nestedopenpos = strpos($textlower, $open_tag, $optionend);
		while($nestedopenpos !== FALSE && $tagend !== FALSE) {
			if($nestedopenpos > $tagend) {
				break;
			}
			$tagend = strpos($textlower, $close_tag, $tagend + $close_tag_len);
			$nestedopenpos = strpos($textlower, $open_tag, $nestedopenpos + $open_tag_len);
		}
		if($tagend === FALSE) {
			$beginsearchpos = $optionend;
			continue;
		}

		$localbegin = $optionend + 1;
		$localtext = $function($tagoptions, substr($text, $localbegin, $tagend - $localbegin), $tagname, $extraargs);

		$text = substr_replace($text, $localtext, $tagbegin, $tagend + $close_tag_len - $tagbegin);

		$beginsearchpos = $tagbegin + strlen($localtext);
	} while($tagbegin !== FALSE);

	return $text;
}

	
?>
